package com.goa.mqtt.client;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 褚永硕
 *
 */
@Component
public class MessageCallback implements MqttCallback {

    @Autowired
    private EmqClient emqClient;
    
    private static final Logger log = LoggerFactory.getLogger(MessageCallback.class);


    /**
     * 丢失了对服务端的连接后触发的回调
     * @param cause
     */
    @Override
    public void connectionLost(Throwable cause) {
        // 资源的清理  重连
        log.info("丢失了对服务端的连接");
        /** TODO
         * 存在问题，如果broker宕机了，那么当前所有订阅的主题会丢失，
         * 可以在每次订阅中存入SQL及NoSQL，防止宕机后重新订阅
         */
        System.out.println("连接断开时。。。"+cause.getMessage());
        while (true){
            //如果获取到true,那么是连接成功的
            if (emqClient.isConnect()){
                log.info("重试连接成功，可以继续发消息了");
                break;
            }
            //重连成功
            log.error("继续重试连接中.......");
            emqClient.reConnect();
            try {
                log.info("防止重试影响性能，每次休眠1s");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 应用收到消息后触发的回调
     * @param topic
     * @param message
     * @throws Exception
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        log.info("订阅者订阅到了消息,topic={},messageid={},qos={},payload={}",
                topic,
                message.getId(),
                message.getQos(),
                new String(message.getPayload()));
    }

    /**
     * 消息发布者消息发布完成产生的回调
     * @param token
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        int messageId = token.getMessageId();
        String[] topics = token.getTopics();
        log.info("消息发布完成,messageid={},topics={}",messageId,topics);
    }
}
